package com.dcivision.framework.taglib.channel;


import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

import javax.servlet.jsp.PageContext;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsCheckoutHistory;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.forum.core.ForumManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.taglib.utility.SourceManage;

public abstract class AjaxStandardRecentDocFormatter extends AbstractAjaxChannelFormatter {

//---------get from parameters-------------------


  //----------should init --------------------------
  protected PermissionManager permissionManager = null;
  protected DocumentRetrievalManager docRetrievalManager = null;
  protected VersionControlManager verControlManager = null;
  protected DocumentValidateManager docValidateManager = null;
  protected ForumManager forumManager= null;
  protected AjaxTagFactory  ajaxFactory = null;

  //---------should init in the method getContent for{....}
  protected DmsDocument dmsDocument = null;
  protected DmsDocument documentRoot = null;
  protected Integer checkoutPersonID = null;//new Integer("0");
  protected String docItemStatus ;//= dmsDocument.getItemStatus();
  protected String permission = "";
  protected String sCurFunctionCode="";
  protected String homePageFunctionCode ;//= DmsOperationConstant.LIST_PERSONAL_HOME;
  protected String sRootType="";
  protected int i;
  protected DmsCheckoutHistory checkoutHistory = null;//new DmsCheckoutHistory();



  public AjaxStandardRecentDocFormatter(){

  }
  public AjaxStandardRecentDocFormatter(PageContext pageContext,int pageSize,List channelList){
    this.pageContext = pageContext;
    this.channelList = channelList;
    this.pageSize = pageSize;
    init();
  }

  public void init(){
    super.init();
    permissionManager = sessionContainer.getPermissionManager();
    docRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn);
    verControlManager = new VersionControlManager(sessionContainer, conn);
    docValidateManager = new DocumentValidateManager(sessionContainer,conn);
    //forumManager=new ForumManager(sessionContainer,conn);
    ajaxFactory = (AjaxTagFactory)pageContext.getRequest().getAttribute(AjaxConstant.AJAXTAGFACTORY);
    columnCount = 2;
    this.pattern="common.channel.document";
  }

  public String[] getContent() throws ApplicationException{
    StringBuffer bstr = new StringBuffer();

    for(Iterator it = channelList.iterator();it.hasNext();){
      i++;
      dmsDocument = (DmsDocument)it.next();
      checkoutHistory = new DmsCheckoutHistory();
      documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());
      checkoutPersonID = new Integer("0");
      docItemStatus = dmsDocument.getItemStatus();
      permission = "";
      sCurFunctionCode="";
      homePageFunctionCode = DmsOperationConstant.LIST_PERSONAL_HOME;
      sRootType="";

      if (DmsVersion.EXCLUSIVE_LOCK.equals(dmsDocument.getItemStatus())) {
        checkoutHistory = verControlManager.getCheckoutHistory(dmsDocument.getCheckoutID());
        checkoutPersonID = checkoutHistory.getCheckoutPersonID();
     }
     //Permission string
     documentRoot = docRetrievalManager.getRootFolderByRootID(dmsDocument.getRootID());

     if (documentRoot!=null) {
       if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getDocumentName())) {
         permission = "PERSONAL";
         sCurFunctionCode = SystemFunctionConstant.DMS_PERSONAL_FOLDER;
       } else {
         //Bill add for EIP-2028
         permission = permissionManager.filterDocumentPermissionByWorkflow(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT,dmsDocument.getID());
         sCurFunctionCode = SystemFunctionConstant.DMS_PUBLIC_FOLDER;
       }
     }

     if(DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())){
       DmsDocument  newDocument = docRetrievalManager.getRelationshipTargetDocument(dmsDocument.getID(),DmsDocument.DOCUMENT_LINK);

       if (newDocument!=null){
         if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(documentRoot.getDocumentName())) {
           permission = "PERSONAL";
           sCurFunctionCode = SystemFunctionConstant.DMS_PERSONAL_FOLDER;
         } else {
           //permission = (String) permissionManager.getPermission(dbConn, GlobalConstant.OBJECT_TYPE_DOCUMENT, newDocument.getID());
           sCurFunctionCode = SystemFunctionConstant.DMS_PUBLIC_FOLDER;
         }
       }
     }

     if("PERSONAL".equals(permission)){
          sRootType=DmsRoot.PERSONAL_ROOT;
     }else{
          sRootType=DmsRoot.PUBLIC_ROOT;
     }

      bstr.append("<tr>");
      bstr.append(getName());
      //bstr.append(getLocation());
      bstr.append(getStatus());
      //bstr.append(getUpdateDate());
      bstr.append("</tr>");
    }
    //bstr.append(this.getPageInfoContent(columnCount));
    //return bstr.toString();
    return this.parsePageInfo(bstr);
  }

  protected abstract String getName() throws ApplicationException;
  protected abstract String getLocation() throws ApplicationException;
  protected abstract String getStatus() throws ApplicationException;
  protected abstract String getUpdateDate() throws ApplicationException;

  protected String getName(StringBuffer bstr) throws ApplicationException{

    if (!DmsVersion.ARCHIVED_STATUS.equals(dmsDocument.getItemStatus())&&(!GlobalConstant.RECORD_STATUS_INACTIVE.equals(dmsDocument.getRecordStatus())))  {
      String targetItemStatus = null;//Add "targetItemStatus" to handle shortcut target archived problem; lee update for bug 6001/5924
      String targetType="";
      String targetPermission = "";
     if(DmsDocument.DOCUMENT_LINK.equals(dmsDocument.getDocumentType())){
       DmsDocument newDocument=docRetrievalManager.getRelationshipTargetDocument(dmsDocument.getID(),DmsDocument.DOCUMENT_LINK);
       if (newDocument!=null){
         targetItemStatus = newDocument.getItemStatus();
         targetType=newDocument.getDocumentType();
         targetPermission = permissionManager.getDocumentLinkPermission(conn, newDocument.getID());
         if(DmsDocument.PAPER_DOC_TYPE.equals(newDocument.getDocumentType())){
           targetType=DmsDocument.PAPER_DOC_TYPE;
         }
       }
     }
    //Update By Jim Zhou      2007/01/26      EIP-1540
    //bstr.append("<a href=\"\" onclick=\"return overlib(FUNCTION, 'getMenuText(\\'"+TextUtility.escapeJSString(TextUtility.escapeJSString(dmsDocument.getDocumentName()))+"\\', \\'"+dmsDocument.getDocumentType()+"\\',  \\'"+dmsDocument.getID()+"\\', \\'"+dmsDocument.getParentID()+"\\', \\'"+dmsDocument.getRootID()+"\\', \\'"+i+"\\', \\'"+docValidateManager.checkExpireDocumentOwner(dmsDocument)+"\\', \\'"+checkoutPersonID+"\\', \\'"+sessionContainer.getUserRecordID()+"\\',\\'"+permission+"\\',\\'"+dmsDocument.getHasRelationship()+"\\',null,\\'"+sRootType+"\\',\\'"+targetType+"\\',null,null,null,null,\\'"+targetItemStatus+"\\',\\'"+targetPermission+"\\')', FULLHTML, TEXTSIZE, 2, WIDTH, 120, OFFSETX, 0, OFFSETY, 0, CENTER, STICKY);\"><img src='"+SourceManage.getImgSrc(pageContext, "IconPopupMenuHome.gif", true, false)+"' align='absmiddle' border='0'/></a>");
    bstr.append("<a href=\"\" onclick=\"return overlib(FUNCTION, 'getMenuText(\\'"+TextUtility.escapeJSString(dmsDocument.getDocumentName().replaceAll("\'","&acute;"))+"\\', \\'"+dmsDocument.getDocumentType()+"\\',  \\'"+dmsDocument.getID()+"\\', \\'"+dmsDocument.getParentID()+"\\', \\'"+dmsDocument.getRootID()+"\\', \\'"+i+"\\', \\'"+docValidateManager.checkExpireDocumentOwner(dmsDocument)+"\\', \\'"+checkoutPersonID+"\\', \\'"+sessionContainer.getUserRecordID()+"\\',\\'"+permission+"\\',\\'"+dmsDocument.getHasRelationship()+"\\',null,\\'"+sRootType+"\\',\\'"+targetType+"\\',null,null,null,null,\\'"+targetItemStatus+"\\',\\'"+targetPermission+"\\')', FULLHTML, TEXTSIZE, 2, WIDTH, 120, OFFSETX, 0, OFFSETY, 0, CENTER, STICKY);\"><img src='"+SourceManage.getImgSrc(pageContext, "IconPopupMenuHome.gif", true, false)+"' align='absmiddle' border='0'/></a>");
    } else {
    bstr.append("<img src='"+SourceManage.getImgSrc(pageContext, "IconTreeSetupOptionDisable.gif", true, false)+"' align='absmiddle' border='0'/>");
    }
    bstr.append("<nobr>");
    //----ADD DOC INFO----------------
    AjaxDocumentInfoTag documentInfo = (AjaxDocumentInfoTag)ajaxFactory.getAjaxTag(pageContext, AjaxConstant.documentInfoTag);
    documentInfo.setDocObject(dmsDocument);
    documentInfo.setRecordStatus(dmsDocument.getRecordStatus());
    documentInfo.setPermission(permission);
    documentInfo.setRootDocument(documentRoot);
    documentInfo.setCurFunctionCode(homePageFunctionCode);
    documentInfo.setIndexFlag("showRecentlyAccessIndexFlag");
    documentInfo.setShowIndexFlag(true);
    bstr.append(documentInfo.getAjaxContent());
    bstr.append("</nobr>");
    ajaxFactory.releaseTag(AjaxConstant.documentInfoTag, documentInfo);
    /*// comment by barbin this function aready write in dms:documentInfo taglib
    if(forumManager.hasDiscussion(GlobalConstant.OBJECT_TYPE_DOCUMENT,dmsDocument.getID())){

     int totalTopic=forumManager.getTopicTotalByObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,dmsDocument.getID());
     int totalReply=forumManager.getReplyTotalByObject(GlobalConstant.OBJECT_TYPE_DOCUMENT,dmsDocument.getID().toString());

     bstr.append("<a href=\"dms/ListDmsForum.do?objectType="+GlobalConstant.OBJECT_TYPE_DOCUMENT+"&objectID="+dmsDocument.getID()+"\" onmouseover=\"return overlib('<table border=0 cellpadding=0 cellspacing=1><tr><td>"+totalTopic+" "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "forum.label.total_topic")+" "+totalReply+" "+MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "forum.columnheader.discussion_replies")+"</td></tr></table>')\" onmouseout=\"return nd();\"><img src=\""+SourceManage.getImgSrc(pageContext, "IconDMSOpDiscussion.gif", true, false)+"\"  align='absmiddle' border='0'/></a>");
    }*/
    return bstr.toString();

  }

  protected String getLocation(StringBuffer bstr) throws ApplicationException{
    if (dmsDocument.getParentID().intValue() !=0 ) {
      AjaxDmsLocationPathTag dmsLocationPath = (AjaxDmsLocationPathTag)ajaxFactory.getAjaxTag(pageContext, AjaxConstant.dmsLocationPathTag);
      dmsLocationPath.setParentID(dmsDocument.getParentID());
      dmsLocationPath.setRootID(dmsDocument.getRootID());
      dmsLocationPath.setPermission(permission);
      dmsLocationPath.setRootDocument(documentRoot);
      dmsLocationPath.setIndexFlag("showRecentlyAccessIndexFlag");
      dmsLocationPath.setShowIndexFlag(true);
      dmsLocationPath.setShowAllPath(false);
      bstr.append("&nbsp;"+dmsLocationPath.getAjaxContent());
      ajaxFactory.releaseTag(AjaxConstant.dmsLocationPathTag, dmsLocationPath);
      }else{
      MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "dms.label.root");
    }
    return bstr.toString();
  }

  protected String getStatus(StringBuffer bstr){
    try{
      if (!DmsVersion.ARCHIVED_STATUS.equals(docItemStatus) && (!GlobalConstant.STATUS_INACTIVE.equals((dmsDocument).getRecordStatus().trim())) && !"PERSONAL".equals(permission)) {
        if ((DmsDocument.DOCUMENT_TYPE.equals((dmsDocument).getDocumentType()))
         || (DmsDocument.COMPOUND_DOC_TYPE.equals((dmsDocument).getDocumentType()))
         || (DmsDocument.EMAIL_DOC_TYPE.equals((dmsDocument).getDocumentType()))
         || (DmsDocument.FORM_DOC_TYPE.equals((dmsDocument).getDocumentType()))
         || (DmsDocument.FLOW_DOC_TYPE.equals((dmsDocument).getDocumentType()))) {
          if (docItemStatus.equals(DmsVersion.EXCLUSIVE_LOCK)) {
            String checkoutUser = UserInfoFactory.getUserFullName(checkoutPersonID);
            //NEED ATTACTION-------------
            //Update By Jim Zhou          2007/01/26        EIP-1450
            bstr.append("<a href=\"javascript://\" onclick=\"return CustOpCheckin("+dmsDocument.getID()+", "+dmsDocument.getParentID()+", "+dmsDocument.getRootID()+", '"+sCurFunctionCode+"', "+checkoutPersonID+", "+sessionContainer.getUserRecordID()+", null,"+dmsDocument.getHasRelationship()+");\" onmouseover=\"return getPopupInfo('<table border=0 cellpadding=0 cellspacing=0><tr><td><img src="+SourceManage.getImgSrc(pageContext, "IconDMSLockHome.gif", true, false)+"  align=absmiddle border=0 /></td><td><nobr>&nbsp;"+checkoutUser+"</nobr></td></tr></table>');\" onmouseout=\"return nd();\"><img src='"+SourceManage.getImgSrc(pageContext, "IconDMSLockHome.gif", true, false)+"' border='0'/></a>");
          } else if (docItemStatus.equals(DmsVersion.ARCHIVED_STATUS)) {
            bstr.append("<img src='"+SourceManage.getImgSrc(pageContext, "IconDMSUnlockHome.gif", true, false)+"'  align=\"absmiddle\" border='0'/>");
          } else {
            if (permission.indexOf("T")>=0 &&
                DmsVersion.AVAILABLE_STATUS.equals(docValidateManager.checkExpireDocumentOwner(dmsDocument)) ){//Add By Jim Zhou       2006/12/18      EIP-1125
              bstr.append("<a href=\"javascript://\" onclick=\"return OpCheckout("+dmsDocument.getID()+", "+dmsDocument.getParentID()+", "+dmsDocument.getRootID()+", '"+sCurFunctionCode+"', null);\">");
              bstr.append("<img src='"+SourceManage.getImgSrc(pageContext, "IconDMSUnlockHome.gif", true, false)+"'  align=\"absmiddle\" border='0'/>");
              bstr.append("</a>");
            }else{
              bstr.append("<img src='"+SourceManage.getImgSrc(pageContext, "IconDMSUnlockHome.gif", true, false)+"' align=\"absmiddle\" border='0'/>");
            }
          }
      }else{
        bstr.append(GlobalConstant.EMPTY_FIELD);
           }
      } else {
        bstr.append(GlobalConstant.EMPTY_FIELD);
      }
    }catch(Exception e){
      bstr.append(GlobalConstant.EMPTY_FIELD);
    }
      return bstr.toString();
  }

  protected String getUpdateDate(StringBuffer bstr){
    bstr.append(new AjaxDataFormat(dmsDocument.getAccessDate(),new Timestamp(System.currentTimeMillis()),"ago").format());
    return bstr.toString();
  }

}
